package handler

import (
	"log"

	order "git.oschina.net/fanbuchi/xgggh/order/proto/order"
	"golang.org/x/net/context"
	"git.oschina.net/fanbuchi/xgggh/order/service"
)

type Order struct{
	service.Order;
}

//micro query com.xgggh.srv.order Orders.Create '{"name": "1分钱会员", "price": 1,"products": [{"stock":2,"id":306737807334604801},{"stock":3,"id":306794106315767809}]}'
func (handler *Order) Create(ctx context.Context, req *order.CreateReq, rsp *order.CreateRsp) error {
	// oauth2Service
	orderRsp,err:=handler.Order.Create(req)
	rsp.Order=orderRsp
	if err!=nil {
		rsp.Code=order.Code_UNKNOWN
		rsp.Detail=err.Error()
	}
	return nil
}


//Query micro query com.xgggh.srv.order Orders.Query '{"id": 308357643048157185}'
func (handler *Order) Query(ctx context.Context, req *order.QueryReq, rsp *order.QueryRsp) error {
	// oauth2Service
	_order,err:=handler.Order.Query(req)
	rsp.Order= _order
	if err!=nil {
		rsp.Code=order.Code_UNKNOWN
		rsp.Detail=err.Error()
	}
	return nil
}


//Update 更新订单金额 用于订单调价
func (handler *Order) Update(ctx context.Context, req *order.UpdateReq, rsp *order.Response) error {
	// oauth2Service
	err:=handler.Order.Update(req)
	if err!=nil {
		rsp.Code=order.Code_UNKNOWN
		rsp.Detail=err.Error()
	}
	return nil
}


// Delete micro query com.xgggh.srv.order Order.Delete '{"id": 306433967028994049}'
func (handler *Order) Delete(ctx context.Context, req *order.DeleteReq, rsp *order.Response) error {
	err:=handler.Order.Delete(req)
	if err!=nil {
		rsp.Code=order.Code_UNKNOWN
		rsp.Detail=err.Error()
	}
	return nil
}


//Search micro query com.xgggh.srv.order Order.Search '{"page_number":1,"result_per_page":2,"params":{"name":"tiyanviper1"}}'
func (handler *Order) Search(ctx context.Context, req *order.SearchReq, rsp *order.SearchRsp) error {
	orders,err:=handler.Order.Search(req)
	rsp.Order = orders
	if err!=nil {
		rsp.Code=order.Code_UNKNOWN
		rsp.Detail=err.Error()
	}
	return nil
}

// Stream is a server side stream handler called via client.Stream or the generated client code
func (handler *Order) Stream(ctx context.Context, req *order.StreamingRequest, stream order.Orders_StreamStream) error {
	log.Printf("Received Example.Stream request with count: %d", req.Count)

	for i := 0; i < int(req.Count); i++ {
		log.Printf("Responding: %d", i)
		if err := stream.Send(&order.StreamingResponse{
			Count: int64(i),
		}); err != nil {
			return err
		}
	}

	return nil
}

// PingPong is a bidirectional stream handler called via client.Stream or the generated client code
func (handler *Order) PingPong(ctx context.Context, stream order.Orders_PingPongStream) error {
	for {
		req, err := stream.Recv()
		if err != nil {
			return err
		}
		log.Printf("Got ping %v", req.Stroke)
		if err := stream.Send(&order.Pong{Stroke: req.Stroke}); err != nil {
			return err
		}
	}
}
